import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Icon, Card, Radio, Progress } from 'antd'
import moment from 'moment'
import _ from 'lodash'
// import HomeMap from './components/homeMap'
// import ProjectMap from './components/projectMap'
import echarts from 'echarts'
import Ajax from 'lib/Ajax'
import { mapColor } from 'lib/fun'
import NewsShow from '../news/components/newsShow'

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;

const getNum = function(percent){
  if(parseInt(percent) == percent){
    return percent
  }else if(parseInt(percent) == percent.toFixed(2)){
    return parseInt(percent)
  }else{
    return percent.toFixed(2)
  }
}

// var option = {
//         title : {
//             show: false,
//             text: '',
//             subtext: '',
//             x:'center'
//         },
//         tooltip : {
//             trigger: 'item',
//             formatter: "{a} <br/>{b} : {c} ({d}%)"
//         },
//         series : [
//             {
//                 name: '项目统计',
//                 type: 'pie',
//                 radius : '55%',
//                 center: ['50%', '50%'],
//                 data: [],
//                 itemStyle: {
//                     emphasis: {
//                         shadowBlur: 10,
//                         shadowOffsetX: 0,
//                         shadowColor: 'rgba(0, 0, 0, 0.5)'
//                     }
//                 }
//             }
//         ]
//     }
const optionTree = {
    tooltip: {
        trigger: 'axis'
    },
    color: ['#937fc7',
            '#ff3e43',
            '#FFBE41',
            '#00b4ff',
            '#39C558',
            '#ff8153',
            '#4acab4'],
    toolbox: {
        feature: {
            dataView: {
              show: true, 
              readOnly: true,
              optionToContent: function(opt) {
                var axisData = opt.xAxis[0].data;
                var series = opt.series;
                
                var table = `<div class="ant-table ant-table-middle ant-table-fixed-header ant-table-scroll-position-left">
                              <div class="ant-table-content">
                                <div class="ant-table-scroll">
                                  <span>
                                    <div class="ant-table-header">
                                      <table class="">
                                        <colgroup>
                                          <col style="width: 150px; min-width: 150px;">
                                          <col style="width: 150px; min-width: 150px;">
                                          <col style="width: 150px; min-width: 150px;">
                                        </colgroup>
                                        <thead class="ant-table-thead">
                                          <tr>
                                            <th class=""><span>日期</span></th>
                                            <th class=""><span>${series[0].name}</span></th>
                                            <th class=""><span>${series[1].name}</span></th>
                                          </tr>
                                        </thead>
                                      </table>
                                    </div>
                                    <div class="ant-table-body" style="max-height: 182px; overflow-y: scroll;">
                                      <table class="">
                                        <colgroup>
                                          <col style="width: 150px; min-width: 150px;">
                                          <col style="width: 150px; min-width: 150px;">
                                          <col style="width: 150px; min-width: 150px;">
                                        </colgroup>
                                        <tbody class="ant-table-tbody">`;
              for (var i = 0, l = axisData.length; i < l; i++) {
                  table += `<tr class="ant-table-row  ant-table-row-level-0">
                              <td class=""><span class="ant-table-row-indent indent-level-0" style="padding-left: 0px;">${axisData[i]}</span></td>
                              <td class=""><span class="ant-table-row-indent indent-level-0" style="padding-left: 0px;">${series[0].data[i]}</span></td>
                              <td class=""><span class="ant-table-row-indent indent-level-0" style="padding-left: 0px;">${series[1].data[i]}</span></td>
                            </tr>`;
              }

              table += `</tbody>
                        </table>
                      </div>
                    </span>
                  </div>
                </div>
              </div>`;

              return table;
            }
          },
          right: 20
        }
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis: [{
        type: 'category',
        boundaryGap: false,
        data: [],
        axisLine: {
          lineStyle: {
            color: '#595959'
          }
        }
    }],
    yAxis: [{
        type: 'value'
    }],
    legend: {
      data:[],
      right: 40
    },
    series: [{
        name: '覆盖人次',
        type: 'line',
        smooth: true,
        // color: '#0f87dd',
        label: {
            normal: {
                show: true,
                position: 'top',
                // textStyle: {
                //   color: '#0f87dd',
                // }
            }
        },
        // lineStyle: {
        //     normal: {
        //       color: '#0f87dd',
        //     }
        // },
        areaStyle: {
            normal: {
              // color: '#0f87dd',
            }
        },
        data: []
    }, {
        name: '覆盖人数',
        type: 'line',
        smooth: true,
        label: {
            normal: {
                show: true,
                position: 'bottom'
            }
        },
        areaStyle: {
            normal: {
              // color: '#0f87dd',
            }
        },
        data: []
    }]
};


class ModuleName extends Component {
	constructor(props) {
    super(props);
    this.state = {
      getHomeStatDTO: {},
      hotProject: [],
      newsList: [],
      getHomeQuickNavList: [],
      dateValue: '1',
      newsId: "",
      visible2: false
    }
  }

  componentDidMount(){
    // 饼图
  	// this.chart = echarts.init(document.getElementById('pie'));
   //  this.chart.setOption(option);
    // 线图
    this.chart2Dom = document.getElementById('treeDom');
    this.chart2 = echarts.init(this.chart2Dom);
    this.chart2.setOption(optionTree);

    this.loadPieData();
    this.loadHotProject();
    this.loadNewsList();
    this.loadQuickNav();
    this.getBatchRegistStatByDate();

    window.addEventListener('resize', this.handleResize); 
  }

  handleResize = (e)=>{  
    // this.chart2.setWidth(this.chart2Dom);
    this.chart2.resize();
  }
  
  componentWillUnmount() {  
    window.removeEventListener('resize', this.handleResize);  
  }

  componentWillReceiveProps(nextProps){
    if(nextProps.common.user&&nextProps.common.user.user&&!this.props.common.user){
      // this.setPieData(false, nextProps.common.user.user.userRole)
    }
  }

  loadQuickNav = ()=>{
    var self = this;
    Ajax({
      url: '/reportCenter/home/getHomeQuickNavList',
      data: {},
      success: function(data){
        self.setState({
          getHomeQuickNavList: data
        });
        
        // self.setPieData(data.part2DTO);
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  loadPieData = ()=>{
    var self = this;
    Ajax({
      url: '/reportCenter/home/getHomeStatDTO',
      data: {},
      success: function(data){
        self.setState({
          getHomeStatDTO: data
        });
        
        // self.setPieData(data.part2DTO);
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  setPieData = (data, userRole)=>{
    var self = this;
    var part2DTO = data||this.state.getHomeStatDTO.part2DTO||{};
    var userRole = userRole?userRole:(self.props.common.user?self.props.common.user.user.userRole:"");
    option.series[0].data = [{
        value: part2DTO.todoNum||0, 
        name: part2DTO.todoNumStr||""
      }, {
        value: part2DTO.treatingAuditorNum||0, 
        name: part2DTO.treatingAuditorNumStr||""
      }, {
        value: part2DTO.allSuccessNum||0, 
        name: part2DTO.allSuccessNumStr||""
      }, {
        value: part2DTO.partSuccessNum||0, 
        name: part2DTO.partSuccessNumStr||""
      }];
    self.chart.setOption(option);
  }

  loadHotProject = ()=>{
    var self = this;   
    Ajax({
      url: '/reportCenter/home/getHotProjectStatList',
      data: {},
      success: function(data){
        self.setState({
          hotProject: data
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  loadNewsList = ()=>{
    var self = this;
    Ajax({
      url: '/news/list',
      data: {
        "currentPage": 1,  //请求页码
        "perPage": 5,   //每页数量
      },
      success: function(data){
        self.setState({
          loading: false,
          newsList: data.list
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  getBatchRegistStatByDate = (date)=>{
    var self = this;
    var time = date||this.state.dateValue;
    var nowTime = moment();
    var startTime = null;
    switch(time){
      case '1': startTime = moment().subtract(7, 'days'); break;
      case '2': startTime = moment().subtract(1, 'months'); break;
      case '3': startTime = moment().subtract(1, 'years'); break;
      default: break;
    }
    Ajax({
      url: '/reportCenter/home/getBatchRegistStatByDate',
      data: {
        "dateBegin": startTime.format('YYYY-MM-DD'),
        "dateEnd": nowTime.format('YYYY-MM-DD')
      },
      success: function(data){
        optionTree.legend.data = [data[1].name, data[0].name];
        optionTree.xAxis[0].data = _.map(data[0].pointList, 'x');
        optionTree.series[1].name = data[0].name;
        optionTree.series[0].name = data[1].name;
        optionTree.series[1].data = _.map(data[0].pointList, 'y');
        optionTree.series[0].data = _.map(data[1].pointList, 'y');

        self.chart2.setOption(optionTree);
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  dataChange = (e)=>{
    this.setState({
      dateValue: e.target.value
    })
    this.getBatchRegistStatByDate(e.target.value);
  }

  renderTitle = () => {
      return <div>
        项目补贴情况<span className="fr" style={{float: 'right'}}>
          <RadioGroup 
            defaultValue="1"
            size="small"
            onChange={this.dataChange}
          >
            <RadioButton value="1">近7日</RadioButton>
            <RadioButton value="2">本月</RadioButton>
            <RadioButton value="3" disabled>今年</RadioButton>
          </RadioGroup>
        </span>
      </div>
  }
  
  render() {
    var self = this;
    const part1DTO = this.state.getHomeStatDTO.part1DTO||{};
    const part2DTO = this.state.getHomeStatDTO.part2DTO||{};
    const userRole = self.props.common.user?self.props.common.user.user.userRole:"";
    const icons = ['setting', 'eye-o', 'solution','search'];
    return (
    	<div className="home out-content">
        <Row gutter={30}>
          <Col span={6}>
            <div className="panel mini-box ot-c">
            {/*
              <span className="picon bg-success">
                <Icon type="setting"></Icon>
              </span>
            */}
              <Icon type="hdd" />
              <div className="box-info">
                <p className="size-h2">{part1DTO.projectNum||0}</p>
                <p className="text-muted">{part1DTO.projectNumStr||""}</p>
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className="panel mini-box">
            {/*
              <span className="picon bg-info">
                <Icon type="setting"></Icon>
              </span>
            */}
              <Icon type="solution" />
              <div className="box-info">
                <p className="size-h2">{part1DTO.treatingNum||0}</p>
                <p className="text-muted">{part1DTO.treatingNumStr||""}</p>
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className="panel mini-box ot-c">
            {/*
              <span className="picon bg-warning">
                <Icon type="setting"></Icon>
              </span>
            */}
              <Icon type="team" />
              <div className="box-info">
                <p className="size-h2">{part1DTO.successNum||0}</p>
                <p className="text-muted">{part1DTO.successNumStr||""}</p>
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className="panel mini-box">
            {/*
              <span className="picon bg-danger">
                <Icon type="setting"></Icon>
              </span>
            */}
              <Icon type="pay-circle-o" />
              <div className="box-info">
                <p className="size-h2">{part1DTO.successMoney||0}</p>
                <p className="text-muted">{part1DTO.successMoneyStr||""}</p>
              </div>
            </div>
          </Col>
        </Row>
        <Row gutter={30}>
          <Col span={12}>
            <Card title="快捷导航">
              <div style={{paddingTop:26, height: 186}}>
                <Row gutter={30}>
                  {
                    this.state.getHomeQuickNavList.map((item, i)=>{
                      return <Col span={12} key={item.name}>
                        <span className="ant-btn ant-btn-primary link">
                          <Link to={item.url} >
                            <Icon type={icons[i]} /> {item.name}
                          </Link>
                        </span>
                      </Col>
                    })
                  }
                </Row>
              </div>
            </Card>
          </Col>
          <Col span={12}>
            <Card title="数据看板">
              <div>
                <div style={{float: 'left', width: 120, lineHeight: '28px',fontSize:14,paddingTop: 33}}>
                  <div>{part2DTO.todoNumStr||""}: {part2DTO.todoNum||0}</div>
                  <div>{part2DTO.treatingAuditorNumStr||""}: {part2DTO.treatingAuditorNum||0}</div>
                  <div>{part2DTO.allSuccessNumStr||""}: {part2DTO.allSuccessNum||0}</div>
                  <div>{part2DTO.partSuccessNumStr||""}: {part2DTO.partSuccessNum||0}</div>
                </div>
                <div style={{marginLeft: 130,textAlign: 'center'}}>
                  <Progress width={150} type="circle" percent={(part2DTO.grantingSuccessRate||0)*100} format={percent => `${getNum(percent)}%`}/>
                  <div style={{paddingTop: 15,fontSize:14}}>完成发放率</div>
                </div>
              </div>
            </Card>
          </Col>
        </Row>

        <Row gutter={30}>
          <Col span={24}>
            <Card title={ this.renderTitle() }>
              <div id="treeDom" style={{height: 300}}></div>
            </Card>
          </Col>
        </Row>

        <Row gutter={30}>
          <Col span={12}>
            <Card title="新闻公告">
              <ul className="news">
                {
                  this.state.newsList.map((item)=>{
                    return <li key={item.newsId}>
                      <a href="javascript:;" onClick={()=>{
                        this.setState({
                          newsId: item.newsId,
                          visible2: true
                        })
                      }}>
                        <span className="time">{item.createTime}</span>
                        <span className="text">{item.title}{item.top?"[置顶]":""}</span>
                      </a>
                    </li>
                  })
                }
              </ul>
            </Card>
          </Col>
          <Col span={12}>
            <Card title="热点项目">
              <ul className="news">
                {
                  this.state.hotProject.map((item)=>{
                    return <li key={item.projectId}>
                      <a href="javascript:;">
                        <span className="time">{item.registerNum}人</span>
                        <span className="text">{item.projectName}</span>
                      </a>
                    </li>
                  })
                }
              </ul>
            </Card>
          </Col>
        </Row>
        <NewsShow
          onClose={()=>{
            this.setState({
              visible2: false
            })
          }}
          newsId={this.state.newsId}
          visible={this.state.visible2}
        />
    	</div>
    )
  }
}

function mapStateToProps(state) {
  return {
    common: state.common
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({  }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(ModuleName)
